package com.cwj.thread.cancelthread;

public class Daemon {
    private Thread excuter;
    private boolean finished;

    public static void main(String[] args) {
        Daemon daemon = new Daemon();
        daemon.execute(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    System.out.println("..");
                }
            }
        });

        daemon.shutdown(1_0000);
    }

    public void execute(Runnable runnable) {
        excuter = new Thread() {
            @Override
            public void run() {
                Thread thread = new Thread(runnable);
                thread.setDaemon(true);
                thread.start();

                try {
                    thread.join();
                    finished = true;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        excuter.start();
    }

    public void shutdown(long millis) {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis <= 0) {
            throw new IllegalArgumentException("timeout value is negative");
        } else {
            while (!finished) {
                long delay = millis - now;
                if (delay < 0) {
                    System.out.println("timeout ..");
                    excuter.interrupt();
                    break;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                now = System.currentTimeMillis() - base;
            }
        }
    }
    
}